package components.game
{
	import SEApp.se_util;
	
	import UIFree.controls.uif_close;
	import UIFree.controls.uif_label;
	import UIFree.controls.uif_leavesBlock;
	import UIFree.uif_component;
	import UIFree.uif_ecomponent;
	import UIFree.uif_loader;
	
	import classes.clt_utils;
	
	import components.base.uif_source;
	import components.clt_list;
	
	import data.clt_data;
	
	import flash.events.Event;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;

	public class clt_votesView extends uif_leavesBlock {
		private var _game_id: uint;
		private var _list: clt_list;
		private var _label: uif_label;
		 
		public function clt_votesView(parent:uif_component, ax:int=0, ay:int=0, awidth:int=0, aheight:int=0) {
			super(parent, ax, ay, awidth, aheight, 'tools');
			var inner: Rectangle = block.getInner();
			_label = (new uif_label(block, inner.x, inner.y, inner.width, 20, 'block-title'));
			
			_list = new clt_list(block, inner.x, inner.y + 20, inner.width, inner.height - 20, [], doSelect);
			new uif_close(block, width-25, 6);
			addEvent(Event.CLOSE, doClose, block);  
		}
		
		public function showVotes(game_id: uint): void {
			if (_game_id != game_id) {
				_game_id = game_id;
				updateList();
			}
			show();
		}
		
		private function doClose(e: Event): void {
			hide();
		}
		
		protected function doSelect(item: Object): void {
			navigateToURL(new URLRequest(item.link));
		}
		
		protected function updateList(): void {
			_list.clearList();
			_label.text = 'Голосовавшие';
			clt.internalServer.getVotes(_game_id, function(a_data: Object): void {
				if (a_data.response[0] && (a_data.response[0] is Array)) {
					var items: Array = a_data.response[0];
					_label.text = 'Последние ' + items.length + ' голосовавших';
					clt.externalServer.getProfiles(se_util.getUids(items), function(list: Array): void {
						list = clt_utils.usersUnion(items, list);
						list.sortOn('time', Array.DESCENDING);
						_list.attachList(list, createItem);
					});
				}
			});
		}
		
		protected function createItem(area: uif_component, item: Object, index: int): uif_ecomponent {
			var inner: Rectangle = area.getInner();
			var ctrl: uif_ecomponent = new uif_ecomponent(area, inner.x, inner.y + index * 45, inner.width, 45, 'listItem');
			(new uif_label(ctrl, 60, 0, inner.width - 60, 25, 'tabBlock')).text = se_util.userName(item);
			(new uif_label(ctrl, 60, 25, inner.width - 60, 20, 'userName')).text = item.time + ', ' + Utils.decline(item.votes, 'голо-с,са,сов');
			var ld: uif_source = (new uif_source(ctrl, 0, 0, 43, 43));
			ld.loadSource(item.pic);
			if (item.votes >= clt_data.VOTEMEGA)
				new uif_loader(ctrl, clt_servers.IMAGE_URL + 'vm30.png', null, 40, 15);
			ld.buttonMode = true;
			return ctrl;
		}
		
		protected function get clt(): clt_clothingBase {
			return app as clt_clothingBase;
		}
	}
}